from django.shortcuts import render
from django.http import JsonResponse

from web.models import VegInfo


def veg_store(request):
    quality_choices = {
        1: '坏',
        2: '一般',
        3: '好'
    }
    vegs = VegInfo.objects.all()
    search_value = request.GET.get("searchValue") or ""
    if search_value:
        vegs = vegs.filter(name__contains=search_value)

    for veg in vegs:
        veg.quality_str = quality_choices.get(veg.quality, "")

    context = {
        'test': '蔬菜仓库',
        'vegetables': vegs,
        'search': search_value
    }
    return render(request, 'vegetables.html', context)


def add_veg(request):
    name = request.POST.get("name") or ""
    from_place = request.POST.get("from_place") or ""
    number = request.POST.get("number") or 0
    price = request.POST.get("price") or ""
    quality = request.POST.get("quality") or 3
    res = {}

    try:
        VegInfo.objects.create(
            name=name,
            from_place=from_place,
            number=number,
            price=price,
            quality=quality,
        )
        res["success"] = 1
    except Exception as e:
        res["success"] = 0
        res["message"] = str(e)

    return JsonResponse(res)


def del_veg(request, veg_id):
    res = {}
    veg = VegInfo.objects.filter(id=veg_id).first()

    if not veg:
        res["success"] = 0
        res["message"] = "要删除的对象不存在"
    else:
        name = veg.name
        veg.delete()
        res["success"] = 1
        res["message"] = f"{name}删除成功"
    return JsonResponse(res)


def edit_veg(request):
    veg_id = request.POST.get("id") or ""
    name = request.POST.get("name") or ""
    from_place = request.POST.get("from_place") or ""
    number = request.POST.get("number") or 0
    price = request.POST.get("price") or ""
    quality = request.POST.get("quality") or 3

    res = {}
    veg = VegInfo.objects.filter(id=veg_id).first()

    if not veg:
        res["success"] = 0
        res["message"] = "要修改的对象不存在"
    else:
        try:
            veg.name = name
            veg.from_place = from_place
            veg.number = number
            veg.price = price
            veg.quality = quality
            veg.save()
            res["success"] = 1
        except Exception as e:
            res["success"] = 0
            res["message"] = str(e)

    return JsonResponse(res)
